package by.grsu.kononovich.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.kononovich.entity.Auto;
import by.grsu.kononovich.table.AutoTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class AutoDao extends AbstractDao<AutoTable, Auto> {

	public AutoDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(final Auto newAuto) {
		newAuto.setId(getNextId());
		final AutoTable autoTable = deserializeFromXml();
		autoTable.getRows().add(newAuto);
		serializeToXml(autoTable);
	}

	@Override
	public void update(Auto entity) {
		final AutoTable autoTable = deserializeFromXml();
		for (final Auto row : autoTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				row.setMark(entity.getMark());
				row.setModel(entity.getModel());
				row.setCost(entity.getCost());
				row.setFreedom(entity.getFreedom());
				break;
			}
		}
		serializeToXml(autoTable);
	}

	@Override
	public Auto get(Serializable id) {
		final AutoTable autoTable = deserializeFromXml();
		for (final Auto row : autoTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}

	@Override
	public List<Auto> getAll() {
		final AutoTable autoTable = deserializeFromXml();
		return autoTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final AutoTable autoTable = deserializeFromXml();
		Auto toBeDeleted = null;
		for (final Auto row : autoTable.getRows()) {
			if (row.getId().equals(id)) {
				toBeDeleted = row;
				break;
			}
		}
		autoTable.getRows().remove(toBeDeleted);
		serializeToXml(autoTable);
	}

	@Override
	protected Class<AutoTable> getTableClass() {
		return AutoTable.class;
	}

}
